package atomic;

import java.util.concurrent.atomic.AtomicReference;

public class CasNumberRange {

    private static class IntPair {
        final int lower;
        final int upper;

        public IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }
    // atomic开都的还有很多类
    private final AtomicReference<IntPair> values = new AtomicReference<CasNumberRange.IntPair>(new IntPair(0, 0));

    // 方法中的每一步都是原子操作
    public void setLower(int low) {
        while (true) {
            IntPair oldV = values.get(); // 每个cpu执行这段代码都是轮训获取,
            if (low > oldV.upper)
                throw new IllegalArgumentException("can not ser lower to " + low + " > upper");
            IntPair newV = new IntPair(low, oldV.upper);
            if (values.compareAndSet(oldV, newV))
                return;
        }
    }

    public static void main(String[] args) {
        CasNumberRange cas = new CasNumberRange();
        cas.setLower(-1);
    }
}
